package com.lmb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmb.bean.Category;
import com.lmb.bean.Dish;
import com.lmb.bean.Setmeal;
import com.lmb.dao.CategoryDao;
import com.lmb.dao.DishDao;
import com.lmb.dao.SetmealDao;
import com.lmb.exception.CustomException;
import com.lmb.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao,Category> implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private DishDao dishDao;

    @Autowired
    private SetmealDao setmealDao;

    @Override
    public void saveCategory(Category category) {
        if (category==null || category.getName()==null){
            throw new CustomException(0,"新增分类名称不能为空！");
        }
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getName,category.getName());
        Category one = categoryDao.selectOne(wrapper);

        if (one!=null){
            throw new CustomException(0,"新增分类名称'"+category.getName()+"'已经存在！");
        }
        categoryDao.insert(category);
    }

    /**
     * 根据id删除分类
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        //1.判断id不为null
        if(id==null){
            throw  new  CustomException(0,"分类删除id不能为空！");
        }

        //2.根据分类id查询菜品表dish进行统计 看当前分类下有没有菜品数据 有，则不能删除     selectCount(Wrapper wrapper)
        LambdaQueryWrapper<Dish> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Dish::getCategoryId,id);
        Integer count = dishDao.selectCount(wrapper1);
        if(count>0){
            throw  new  CustomException(0,"当前分类下存在关联菜品，无法删除！");
        }

        //3.根据分类id查询套餐表setmeal进行统计 看当前分类下有没有套餐数据 有，则不能删除
        LambdaQueryWrapper<Setmeal> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Setmeal::getCategoryId,id);
        Integer count1 = setmealDao.selectCount(wrapper2);
        if(count1>0){
            throw  new  CustomException(0,"当前分类下存在关联套餐，无法删除！");
        }
        System.out.println("count1 = " + count1);
        //4.以上都通过了 该分类下没有菜品或套餐数据 则可以删除
        categoryDao.deleteById(id);
    }

    @Override
    public void updateCategory(Category category) {
        //1.判断用户提交的分类修改数据中分类名称不能和其他分类名称重复
        //查询条件：name：分类名称  id：分类id  根据名称为name且id不等于当前这个分类id进行查询统计
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getName,category.getName());
        wrapper.ne(Category::getId,category.getId());       //ne:不等于
        Integer count = categoryDao.selectCount(wrapper);
        if(count>0){
            throw  new  CustomException(0,"当前分类名称已存在，请设置为其他的！");
        }

        //2.执行修改操作
        categoryDao.updateById(category);
    }
}
